package com.example.gokuplayalong.bases.alipay.directpay;

import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.custom.textwatcher.CustomLimitInputTextWatcher;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.users.receive.UserMainReceiveUserInfo;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DirectPayMerchantCreate#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class DirectPayMerchantCreate extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;

    private ImageView mDirectPayMerchantCreateIv;
    private TextView mDirectPayMerchantCreateUnpassreasonShow;
    private LinearLayout mDirectPayMerchantCreateBodyType;
    private TextView mDirectPayMerchantCreateBodyTypeShow;
    private CardView mDirectPayMerchantCreateCompanies;

    private EditText mDirectPayMerchantCreateCompaniesLicenseNo;
    private EditText mDirectPayMerchantCreateCompaniesMerchantAbbreviation;
    private EditText mDirectPayMerchantCreateCompaniesLegalPersonName;
    private EditText mDirectPayMerchantCreateCompaniesLegalPersonCardNo;
    private EditText mDirectPayMerchantCreateContactName;
    private EditText mDirectPayMerchantCreateContactPhone;
    private EditText mDirectPayMerchantCreateContactMailbox;
    private EditText mDirectPayMerchantCreateAlipayCount;
    private CardView mDirectPayMerchantCreateIndividual;
    private EditText mDirectPayMerchantCreateIndividualName;
    private EditText mDirectPayMerchantCreateIndividualCardNo;
    private EditText mDirectPayMerchantCreateIndividualMerchantAbbreviation;
    private Button mDirectPayMerchantCreateSubmit;
    private LinearLayout mDirectPayMerchantCreateStep1;
    private LinearLayout mDirectPayMerchantCreateStep2;

    JSONObject data = new JSONObject();


    List<String> companiesNameList = Arrays.asList("companiesLicenseNo", "companiesMerchantAbbreviation", "companiesLegalPersonName", "companiesLegalPersonCardNo", "contactName", "contactPhone", "contactMailbox", "alipayCount");
    List<String> individualNameList = Arrays.asList("individualName", "individualCardNo", "individualMerchantAbbreviation", "contactName", "contactPhone", "contactMailbox", "alipayCount");

    public DirectPayMerchantCreate() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DirectPayMerchantCreate.
     */
    // TODO: Rename and change types and number of parameters
    public static DirectPayMerchantCreate newInstance(String param1, String param2) {
        DirectPayMerchantCreate fragment = new DirectPayMerchantCreate();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_direct_pay_merchant_create, container, false);
        initView();
        return rootView;
    }

    private void initView() {

        mDirectPayMerchantCreateIv = rootView.findViewById(R.id.direct_pay_merchant_create_iv);
        mDirectPayMerchantCreateUnpassreasonShow = rootView.findViewById(R.id.direct_pay_merchant_create_unpassreason_show);
        mDirectPayMerchantCreateBodyType = rootView.findViewById(R.id.direct_pay_merchant_create_body_type);
        mDirectPayMerchantCreateBodyTypeShow = rootView.findViewById(R.id.direct_pay_merchant_create_body_type_show);
        mDirectPayMerchantCreateCompanies = rootView.findViewById(R.id.direct_pay_merchant_create_companies);
        mDirectPayMerchantCreateCompaniesLicenseNo = rootView.findViewById(R.id.direct_pay_merchant_create_companies_license_no);
        mDirectPayMerchantCreateCompaniesMerchantAbbreviation = rootView.findViewById(R.id.direct_pay_merchant_create_companies_merchant_abbreviation);
        mDirectPayMerchantCreateCompaniesLegalPersonName = rootView.findViewById(R.id.direct_pay_merchant_create_companies_legal_person_name);
        mDirectPayMerchantCreateCompaniesLegalPersonCardNo = rootView.findViewById(R.id.direct_pay_merchant_create_companies_legal_person_card_no);
        mDirectPayMerchantCreateContactName = rootView.findViewById(R.id.direct_pay_merchant_create_contact_name);
        mDirectPayMerchantCreateContactPhone = rootView.findViewById(R.id.direct_pay_merchant_create_contact_phone);
        mDirectPayMerchantCreateContactMailbox = rootView.findViewById(R.id.direct_pay_merchant_create_contact_mailbox);
        mDirectPayMerchantCreateAlipayCount = rootView.findViewById(R.id.direct_pay_merchant_create_alipay_count);
        mDirectPayMerchantCreateIndividual = rootView.findViewById(R.id.direct_pay_merchant_create_individual);
        mDirectPayMerchantCreateIndividualName = rootView.findViewById(R.id.direct_pay_merchant_create_individual_name);
        mDirectPayMerchantCreateIndividualCardNo = rootView.findViewById(R.id.direct_pay_merchant_create_individual_card_no);
        mDirectPayMerchantCreateIndividualMerchantAbbreviation = rootView.findViewById(R.id.direct_pay_merchant_create_individual_merchant_abbreviation);
        mDirectPayMerchantCreateStep1 = rootView.findViewById(R.id.direct_pay_merchant_create_step1);
        mDirectPayMerchantCreateStep2 = rootView.findViewById(R.id.direct_pay_merchant_create_step2);
        mDirectPayMerchantCreateSubmit = rootView.findViewById(R.id.direct_pay_merchant_create_submit);

        mDirectPayMerchantCreateCompaniesLicenseNo.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateCompaniesLicenseNo));
        mDirectPayMerchantCreateCompaniesMerchantAbbreviation.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateCompaniesMerchantAbbreviation));
        mDirectPayMerchantCreateCompaniesLegalPersonName.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateCompaniesLegalPersonName));
        mDirectPayMerchantCreateCompaniesLegalPersonCardNo.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateCompaniesLegalPersonCardNo));
        mDirectPayMerchantCreateContactName.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateContactName));
        mDirectPayMerchantCreateContactPhone.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateContactPhone));
        mDirectPayMerchantCreateContactMailbox.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateContactMailbox));
        mDirectPayMerchantCreateAlipayCount.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateAlipayCount));
        mDirectPayMerchantCreateIndividualName.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateIndividualName));
        mDirectPayMerchantCreateIndividualCardNo.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateIndividualCardNo));
        mDirectPayMerchantCreateIndividualMerchantAbbreviation.addTextChangedListener(new CustomLimitInputTextWatcher(mDirectPayMerchantCreateIndividualMerchantAbbreviation));


        mDirectPayMerchantCreateIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchBackOnSysFragment();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });


        mDirectPayMerchantCreateBodyType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;

                    BottomMenu.show(new String[]{"企业", "个体工商户", "个人"})
                            .setTitle("请选择主体类型")
                            .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                                @Override
                                public boolean onClick(BottomMenu dialog, CharSequence text, int index) {
                                    if (index == 0) {
                                        data.put("bodyType", "企业");
                                        mDirectPayMerchantCreateCompanies.setVisibility(View.VISIBLE);
                                        mDirectPayMerchantCreateIndividual.setVisibility(View.GONE);
                                        mDirectPayMerchantCreateBodyTypeShow.setText("企业");
                                    }
                                    else if (index == 1) {
                                        data.put("bodyType", "个体工商户");
                                        mDirectPayMerchantCreateCompanies.setVisibility(View.VISIBLE);
                                        mDirectPayMerchantCreateIndividual.setVisibility(View.GONE);
                                        mDirectPayMerchantCreateBodyTypeShow.setText("个体工商户");
                                    }
                                    else if (index == 2) {
                                        data.put("bodyType", "个人");
                                        mDirectPayMerchantCreateCompanies.setVisibility(View.GONE);
                                        mDirectPayMerchantCreateIndividual.setVisibility(View.VISIBLE);
                                        mDirectPayMerchantCreateBodyTypeShow.setText("个人");

                                    }
                                    return false;
                                }
                            });
                } catch (Throwable e) {

                }
            }
        });
        mDirectPayMerchantCreateSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;

                    if (StringUtils.isEmpty(data.getString("bodyType"))) {
                        AppParams.getInstance().deshakLast = 0;
                        mDirectPayMerchantCreateBodyType.performClick();
                        return;
                    }
                    data.put("contactName", mDirectPayMerchantCreateContactName.getText()
                            .toString());
                    data.put("contactPhone", mDirectPayMerchantCreateContactPhone.getText()
                            .toString());
                    data.put("contactMailbox", mDirectPayMerchantCreateContactMailbox.getText()
                            .toString());
                    data.put("alipayCount", mDirectPayMerchantCreateAlipayCount.getText()
                            .toString());

                    if (Objects.equals(data.getString("bodyType"), "企业") || Objects.equals(data.getString("bodyType"), "个体工商户")) {

                        data.put("companiesLicenseNo", mDirectPayMerchantCreateCompaniesLicenseNo.getText()
                                .toString());
                        data.put("companiesMerchantAbbreviation", mDirectPayMerchantCreateCompaniesMerchantAbbreviation.getText()
                                .toString());
                        data.put("companiesLegalPersonName", mDirectPayMerchantCreateCompaniesLegalPersonName.getText()
                                .toString());
                        data.put("companiesLegalPersonCardNo", mDirectPayMerchantCreateCompaniesLegalPersonCardNo.getText()
                                .toString());


                        for (int i = 0; i < companiesNameList.size(); i++) {
                            if (StringUtils.isEmpty(data.getString(companiesNameList.get(i)))) {
                                PopTip.show("未填写完成");
                                return;
                            }
                        }


                    }
                    else if (Objects.equals(data.getString("bodyType"), "个人")) {
                        data.put("individualName", mDirectPayMerchantCreateIndividualName.getText()
                                .toString());
                        data.put("individualCardNo", mDirectPayMerchantCreateIndividualCardNo.getText()
                                .toString());
                        data.put("individualMerchantAbbreviation", mDirectPayMerchantCreateIndividualMerchantAbbreviation.getText()
                                .toString());

                        for (int i = 0; i < individualNameList.size(); i++) {
                            if (StringUtils.isEmpty(data.getString(individualNameList.get(i)))) {
                                PopTip.show("未填写完成");
                                return;
                            }
                        }
                    }


                    Beans beansIn = new Beans();
                    beansIn.getJsonObject()
                            .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                    .getString("phone"));
                    beansIn.getJsonObject().put("data", data.toJSONString());

                    AppParams.getNewNetWork()
                            .setInterface(new NetWorkInterface() {
                                @Override
                                public int success(String msg) {
                                    requireActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                JSONObject msgFromServer = JSON.parseObject(msg);
                                                if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                    PopTip.show("提交成功!");
                                                    SysManagerFragments.switchBackOnSysFragment();
                                                }
                                            } catch (Throwable e) {

                                            }
                                        }
                                    });
                                    return 0;
                                }

                                @Override
                                public int failed(String msg) {
                                    return 0;
                                }
                            })
                            .execute(AppParams.getInstance().baseUrl + "/merchantsCreate", beansIn.getJsonObject()
                                    .toJSONString());


                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
    }

    private void initChanged() {
        try {
            mDirectPayMerchantCreateStep1.setVisibility(View.VISIBLE);
            mDirectPayMerchantCreateStep2.setVisibility(View.GONE);
            getMerchantInfo();
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void getMerchantInfo() {
        try {

            Beans beansIn = new Beans();
            beansIn.getJsonObject()
                    .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                            .getString("phone"));

            AppParams.getNewNetWork()
                    .setInterface(new NetWorkInterface() {
                        @Override
                        public int success(String msg) {

                            requireActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject msgFromServer = JSON.parseObject(msg);
                                        if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                            JSONObject merchantInfo = JSON.parseObject(msgFromServer.getString("merchantInfo"));
                                            if (merchantInfo.getString("status")
                                                    .contains("待审核")) {
                                                mDirectPayMerchantCreateUnpassreasonShow.setVisibility(View.VISIBLE);
                                                mDirectPayMerchantCreateUnpassreasonShow.setText("审核中，请耐心等待。如需修改，可重复提交。");
                                            }
                                            else if (merchantInfo.getString("status")
                                                    .contains("审核不通过")) {
                                                mDirectPayMerchantCreateUnpassreasonShow.setVisibility(View.VISIBLE);
                                                mDirectPayMerchantCreateUnpassreasonShow.setText(merchantInfo.getString("status"));
                                                mDirectPayMerchantCreateStep1.setVisibility(View.VISIBLE);
                                                mDirectPayMerchantCreateStep2.setVisibility(View.GONE);

                                            }
                                            else if (Objects.equals(merchantInfo.getString("status"), "待签约")) {
                                                mDirectPayMerchantCreateStep1.setVisibility(View.GONE);
                                                mDirectPayMerchantCreateStep2.setVisibility(View.VISIBLE);
                                            }

                                        }
                                    } catch (Throwable e) {
                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                    }
                                }
                            });
                            return 0;
                        }

                        @Override
                        public int failed(String msg) {
                            return 0;
                        }
                    })
                    .execute(AppParams.getInstance().baseUrl + "/getMerchantInfo", beansIn.getJsonObject()
                            .toJSONString());
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}